package main.social.service.util;

import java.io.*;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class Utils {
	public static String EntryPath = "E:\\DevTool\\apache-tomcat-6.0.36\\webapps\\social\\Upload";
	
	public static boolean SendMail(String mailto, String subject, String body) {
		Properties prop = System.getProperties();
		prop.put("mail.smtp.host", "smtp.gmail.com");
		prop.put("mail.smtp.port", 587);
		prop.put("mail.smtp.starttls.enable", true);
		prop.put("mail.smtp.auth", true);
		final String from = "Social_network_102@gmail.com";
		final String pwd = "willbefixed";
		Authenticator pa = new Authenticator() {
			@SuppressWarnings("unused")
			public PasswordAuthentication getPasswordAthentication() {
				return new PasswordAuthentication(from, pwd);
			}
		};
		Session session = Session.getInstance(prop, pa);
		Message msg = new MimeMessage(session);
		try {
			msg.setFrom(new InternetAddress(from));
			msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(mailto));
			msg.setSubject(subject);
			msg.setText(body);
			msg.setHeader("Active-Mail", "Social Account active");
			msg.setSentDate(new Date());
			msg.saveChanges();
			Transport.send(msg);
		} catch (AddressException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			return false;
		}
		return true;
	}

	public static boolean Savefile(CommonsMultipartFile fileData,
			String saveName) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			if (fileData.getSize() > 0) {
				if (fileData.getSize() > 100000) {
					return false;
				}
				File imageFile = new File(saveName);
				if(imageFile.exists()){
					return false;
				}else{
					imageFile.createNewFile();
				}
				inputStream = fileData.getInputStream();
				outputStream = new FileOutputStream(imageFile);
				int readBytes = 0;
				byte[] buffer = new byte[10000];
				while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
					outputStream.write(buffer, 0, readBytes);
				}
				outputStream.close();
				inputStream.close();
				
			}
		} catch (IOException ioe) {
			return false;
		}
		return true;
	}

	public static String createUUIDCode(int length){
		String result = UUID.randomUUID().toString().substring(0, length);
		return result;
	}
}
